package org.example.afiona.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import org.example.afiona.common.VO.ResultVO;
import org.example.afiona.common.utils.ResultVOUtil;
import org.example.afiona.service.VO.OrderInfoVO;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @Author: leo
 * @date: 2021/7/1
 */
@RestController
public class OrderController {
    @GetMapping("hystrix/test")
    @HystrixCommand(fallbackMethod = "timeoutHandler",commandProperties = {
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value="2000"),
            // 开启断路器
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            // 请求次数
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "2"),
            // 时间窗口期
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
            // 失败率
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "50")
    })
    public ResultVO<List<OrderInfoVO>> getOrderListByUserId(Integer userId) {
        //        int x = 10/0;
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        List<OrderInfoVO> orderInfoVOList = Stream.of(1, 2, 3).map(e -> {
            OrderInfoVO vo = new OrderInfoVO();
            vo.setOrderId(String.valueOf(e));
            vo.setAmount(new BigDecimal(String.valueOf(e * 100)));
            return vo;
        }).collect(Collectors.toList());
        return ResultVOUtil.success(orderInfoVOList);
    }

    public ResultVO<List<OrderInfoVO>> timeoutHandler(Integer userId) {

        return ResultVOUtil.error(500,"order服务开启熔断");
    }

}
